package com.yicong.ants.ui.video;

import android.os.Bundle;
import android.util.Pair;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;

import com.cchao.simplelib.core.Router;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.model.event.CommonEvent;
import com.cchao.simplelib.ui.activity.BaseStatefulActivity;
import com.cchao.simplelib.util.StringHelper;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.bean.HomePageBean;
import com.yicong.ants.databinding.ActivityVideoHomeBinding;
import com.yicong.ants.manager.BusinessHelper;
import com.yicong.ants.manager.UserManager;
import com.yicong.ants.manager.http.RetrofitHelper;
import com.yicong.ants.utils.StatusBarUtil;
import com.yicong.ants.utils.ToastUtils;
import com.yicong.ants.view.popup.CommonSharePopup;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 短视频主页
 */
public class VideoProfileActivity extends BaseStatefulActivity<ActivityVideoHomeBinding> implements View.OnClickListener {

    List<Pair<String, Fragment>> mContent;
    boolean mIsSelf;
    boolean mIsFollow;
    String mProfileUid;
    HomePageBean mHomePageBean;
    boolean isLoad;

    @Override
    protected int getLayout() {
        return R.layout.activity_video_home;
    }

    @Override
    protected void initEventAndData() {
        StatusBarUtil.setStatusImmerAndTextWhite(getWindow());
        mIsFollow = getIntent().getBooleanExtra(Constants.Extra.Video_isFocus, false);
        mProfileUid = getIntent().getStringExtra(Constants.Extra.Uid);
        mDataBind.adViewTimer.startTime(mDisposable);
        init();

    }

    public Fragment getFragments(String type, int pageIndex) {
        Fragment fragment = new VideoHomeFragment().setPageIndex(pageIndex);
        Bundle bundle = new Bundle();
        bundle.putString(Constants.Extra.Type, type);
        bundle.putString(Constants.Extra.Uid, mProfileUid);

        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);
        switch (event.getCode()) {
            case Constants.Event.Video_Follow_Update:
                for (Map.Entry<String, Boolean> entry : BusinessHelper.mVideoFocus.entrySet()) {
                    if (entry.getKey().equalsIgnoreCase(mProfileUid)) {
                        mIsFollow = entry.getValue();
                        updateFollow();
                        break;
                    }
                }
                break;
            case Constants.Event.Video_Del_Update:
                finish();
                break;
        }
    }

    void init() {
        if (UserManager.notLogin()) {
            mIsSelf = false;
        } else if (UserManager.getUserId().equals(mProfileUid)) {
            mIsSelf = true;
        }
        mDataBind.setClick(this);

        updateFollow();
        UiHelper.setVisibleElseGone(mDataBind.myhome, mIsSelf);
        UiHelper.setVisibleElseGone(mDataBind.follow, !mIsSelf);
        onLoadData();
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    private void initViewPager() {
        mContent = new ArrayList<>();
        mContent.add(Pair.create("作品 " + StringHelper.null2Space(mHomePageBean.getVideo_qty()), getFragments("2", 0)));
        mContent.add(Pair.create("喜欢 " + StringHelper.null2Space(mHomePageBean.getLike_qty()), getFragments("0", 1)));
        mDataBind.viewPage.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int i) {
                return mContent.get(i).second;
            }

            @Override
            public int getCount() {
                return mContent.size();
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return mContent.get(position).first;
            }
        });

        mDataBind.tabLayout.setViewPager(mDataBind.viewPage);
        mDataBind.tabLayout.onPageSelected(0);
        mDataBind.viewPage.setCurrentItem(0);
        mDataBind.viewPage.setOffscreenPageLimit(mContent.size());
    }

    @Override
    protected void onLoadData() {
        addSubscribe(RetrofitHelper.getApis().videoHomePage(mProfileUid)
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    if (respBean.isCodeFail()) {
                        return;
                    }
                    mHomePageBean = respBean.getData();
                    mDataBind.setBean(respBean.getData());
                    if (isLoad) {
                        mContent.add(Pair.create("作品 " + StringHelper.null2Space(mHomePageBean.getVideo_qty()), getFragments("2", 0)));
                        mContent.add(Pair.create("喜欢 " + StringHelper.null2Space(mHomePageBean.getLike_qty()), getFragments("0", 1)));
                    } else {
                        initViewPager();
                        isLoad = true;
                    }
                }, RxHelper.getErrorConsumer()));
    }

    private void updateFollow() {
        mDataBind.follow.setText(mIsFollow ? "取消关注" : "+ 关注");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.share:
                // ants://platform/app?id=11070&uid=xx;
                String link = "ants://platform/app?id=11071&uid=" + mHomePageBean.getUid();

                new CommonSharePopup(thisActivity)
                        .setTitle(mHomePageBean.getNickname() + " 的主页", link)
                        .showPopupWindow(view);

                break;
            case R.id.follow:
                Map<String, String> focusMap = new HashMap<>();
                focusMap.put("author_uid", mProfileUid);

                addSubscribe(RetrofitHelper.getApis().videoFocus(focusMap)
                        .compose(RxHelper.toMain())
                        .subscribe(respBean -> {
                            hideProgress();
                            if (respBean.isCodeFail()) {
                                showToast(respBean.getMsg());
                                return;
                            }
                            mIsFollow = !mIsFollow;
                            showToast(mIsFollow ? "已关注" : "取消关注");
                            updateFollow();
                            BusinessHelper.putFollow(mProfileUid, mIsFollow);
                        }, RxHelper.getHideProgressConsumer(this)));
                break;

            case R.id.presentrecord:
                Router.turnTo(mContext, MyGiftListActivity.class).start();
                break;
            case R.id.ll_focus:
                if (mHomePageBean == null) {
                    ToastUtils.showShort(this, "网络异常，请稍后重试");
                    return;
                }
                Router.turnTo(mContext, FocusListActivity.class)
                        .putExtra(Constants.Extra.Uid, mProfileUid)
                        .putExtra(Constants.Extra.Name, mHomePageBean.getNickname()).start();
                break;
        }
    }
}
